<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <!-- canvas画笔 -->
    <canvas id="draw" width="800" height="800"></canvas>

    <script>
        // 获取canvas元素
        const canvas = document.querySelector('#draw');
        // 重新设置画布高度宽度
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        // 获取一个2d效果的context对象
        const ctx = canvas.getContext('2d')
        // console.log(ctx);
        ctx.strokeStyle = '#BADA55' //初始颜色
        ctx.lineJoin = 'round' // 交叉点类型
        ctx.lineCap = 'round' // 线末端类型
        ctx.lineWidth = 50// 线条宽度
        ctx.globalCompositeOperation = 'multiply' // 允许颜色叠加

        let idDrawing = false;
        let lastX = 0
        let lastY = 0
        let hue = 0
        let direction = true
        function draw(e) {
            if (!idDrawing) return;
            ctx.strokeStyle = `hsl(${hue},100%,50%)` //(颜色，饱和度，明暗度)
            ctx.beginPath() // 开始一个新的路径 将之前的路径清空
            ctx.moveTo(lastX, lastY) // 移动路径的开始点到指定的位置
            ctx.lineTo(e.offsetX, e.offsetY) // 结束点
            ctx.stroke() // 描边

            // 更新起始点的位置
            lastX = e.offsetX
            lastY = e.offsetY
            // [lastX, lastY] = [e.offsetX, e.offsetY]
            hue++
            if (hue > 359) { hue = 0 }

            if( ctx.lineWidth >=100 || ctx.lineWidth<=1 ) {
                direction = !direction
            }
            if (direction) {
                ctx.lineWidth++
            } else ctx.lineWidth--
            // console.log(e); //--- 鼠标路径

        }
        canvas.addEventListener('mousemove', draw)// 监听canvas对象的动作
        canvas.addEventListener('mousedown', (e) => {
            idDrawing = true;
            lastX = e.offsetX
            lastY = e.offsetY
            // [lastX, lastY] = [e.offsetX, e.offsetY];

        })// 监听鼠标是否按下的动作
        canvas.addEventListener('mouseup', () => idDrawing = false)// 监听鼠标是否按下的动作
        canvas.addEventListener('mouseout', () => idDrawing = false)// 监听鼠标是移出画布

    </script>
</body>

</html>